<template>
  <div class="address">
    <Header title="编辑收货地址" :hasRight="true" @save="saveAddress" />

    <nut-form :model-value="formData" :rules="formRules" ref="ruleForm">
      <nut-form-item label="收件姓名" prop="name">
        <nut-input v-model="formData.name" class="nut-input-text" type="text" />
      </nut-form-item>
      <nut-form-item label="联系电话" prop="phone">
        <nut-input
          v-model="formData.phone"
          class="nut-input-text"
          type="text"
        />
      </nut-form-item>
      <nut-cell
        :title="selectedAddressName"
        is-link
        @click="visibleStatus.address = true"
      ></nut-cell>
      <nut-form-item label="详细地址" prop="addressDetail">
        <nut-input
          v-model="formData.addressDetail"
          class="nut-input-text"
          type="text"
        />
      </nut-form-item>
    </nut-form>

    <nut-address
      v-model="selectedAddressIdList"
      v-model:visible="visibleStatus.address"
      :province="areaInfo.province"
      :city="areaInfo.city"
      :country="areaInfo.country"
      :town="areaInfo.town"
      @change="handleAreaSelected"
      @close="handleAreaSelectedFinished"
      custom-address-title="请选择所在地区"
    ></nut-address>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, getCurrentInstance } from "vue";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();

import areaOriginData from "@/api/areaData.js";

// 省市区json数据
const areaData = reactive(areaOriginData);

// 省市区信息
const areaInfo = reactive({
  province: [],
  city: [],
  country: [],
  town: [],
});

// 可见状态管理
const visibleStatus = reactive({
  address: false,
});

// 表单数据
const ruleForm = ref(null);
const formData = reactive({
  id: route.query.addressId,
  name: "",
  phone: "",
  provinceId: "",
  provinceName: "",
  cityId: "",
  cityName: "",
  countryId: "",
  countryName: "",
  addressDetail: "",
});

// 表单校验规则
const formRules = reactive({
  name: [{ required: true, message: "请填写收件姓名" }],
  phone: [{ required: true, message: "请填写联系电话" }],
  addressDetail: [{ required: true, message: "请填写详细地址" }],
});

// 获取重复提交token
const getRepeatSubmitToken = () => {
  proxy.$thirdApi.common
    .repeatSubmitToken()
    .then((res) => {
      formData.repeatSubmitToken = res.data;
    })
    .catch((error) => {});
};

// 地址选择事件
const handleAreaSelected = (item) => {
  if (item.custom == "province") {
    areaInfo.city = proxy.$areaUtils.cityList(areaData, item.value.id);
  } else if (item.custom == "city") {
    areaInfo.country = proxy.$areaUtils.countryList(
      areaData,
      item.value.parentId,
      item.value.id
    );
  }
};

// 初始化选中的地址ID列表
const selectedAddressName = ref("选择地址");
const selectedAddressIdList = ref();
const initSelectedAddressIdList = () => {
  areaInfo.province = proxy.$areaUtils.provinceList(areaData);
  areaInfo.city = proxy.$areaUtils.cityList(areaData, formData.provinceId);
  areaInfo.country = proxy.$areaUtils.countryList(
    areaData,
    formData.provinceId,
    formData.cityId
  );
  selectedAddressIdList.value = [
    formData.provinceId,
    formData.cityId,
    formData.countryId,
  ];
  selectedAddressName.value =
    "已选地址：" +
    formData.provinceName +
    formData.cityName +
    formData.countryName;
};

// 地址选择完毕事件
const handleAreaSelectedFinished = (address) => {
  formData.provinceId = address.data.province.id;
  formData.provinceName = address.data.province.name;
  formData.cityId = address.data.city.id;
  formData.cityName = address.data.city.name;
  formData.countryId = address.data.country.id;
  formData.countryName = address.data.country.name;
  selectedAddressName.value = "已选地址：" + address.data.addressStr;
};

// 页面加载完成逻辑
onMounted(() => {
  // 获取重复提交token
  getRepeatSubmitToken();
  // 获取地址详情
  getAddressInfo();
  if (!formData.id) {
    // 初始化地址选择插件
    Object.assign(areaInfo, proxy.$areaUtils.initData(areaData));
  }
});

// 获取地址详情
const getAddressInfo = () => {
  if (formData.id) {
    proxy.$memberApi.address.info(formData.id).then((res) => {
      Object.assign(formData, res.data);
      // 初始化选中的地址ID列表
      initSelectedAddressIdList();
    });
  }
};

// 保存地址
const saveAddress = () => {
  ruleForm.value.validate().then(({ valid, errors }) => {
    if (valid) {
      if (
        !formData.provinceName ||
        !formData.cityName ||
        !formData.countryName
      ) {
        proxy.$showToast.fail("请选择地址");
        return;
      }
      formData.memberId = proxy.$userUtils.getUserId();
      formData.defaultAddress = 0;
      if (formData.id) {
        proxy.$memberApi.address.update(formData).then((res) => {
          router.back();
        });
      } else {
        proxy.$memberApi.address.save(formData).then((res) => {
          router.back();
        });
      }
    }
  });
};
</script>

<style lang="less" scoped>
.address {
}
</style>